/*
 * Copyright 2014-2025 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package org.jetbrains.dokka.kotlinPlaygroundSamples

import org.jetbrains.dokka.pages.*
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.plugability.configuration
import org.jetbrains.dokka.transformers.pages.PageTransformer

internal class KotlinPlaygroundSamplesScriptsInstaller(private val dokkaContext: DokkaContext) : PageTransformer {

    private val kotlinPlaygroundServer =
        configuration<KotlinPlaygroundSamplesPlugin, KotlinPlaygroundSamplesConfiguration>(dokkaContext)?.kotlinPlaygroundServer

    private val scriptsPages = "scripts/kotlin-playground-samples.js"

    override fun invoke(input: RootPageNode): RootPageNode =
        input.let { root ->
            if (dokkaContext.configuration.delayTemplateSubstitution) root
            else {
                if (kotlinPlaygroundServer == null) {
                    root.modified(children = input.children + scriptsPages.toRenderSpecificResourcePage())
                } else {
                    val modifiedScript = modifyScript()

                    root.modified(
                        children = input.children +
                                RendererSpecificResourcePage(
                                    scriptsPages,
                                    emptyList(),
                                    RenderingStrategy.Write(modifiedScript)
                                )
                    )
                }
            }
        }

    private fun modifyScript(): String {
        val scriptContent = javaClass.getResource("/dokka/$scriptsPages")
            ?.readText()
            ?: throw IllegalStateException("Script /dokka/$scriptsPages not found in resources")

        return scriptContent.replace(
            "const kotlinPlaygroundServer = null",
            "const kotlinPlaygroundServer = \"$kotlinPlaygroundServer\""
        )
    }
}

internal class KotlinPlaygroundSamplesStylesInstaller(private val dokkaContext: DokkaContext) : PageTransformer {
    private val stylesPages = "styles/kotlin-playground-samples.css"

    override fun invoke(input: RootPageNode): RootPageNode =
        input.let { root ->
            if (dokkaContext.configuration.delayTemplateSubstitution) root
            else root.modified(children = input.children + stylesPages.toRenderSpecificResourcePage())
        }
}

private fun String.toRenderSpecificResourcePage() = RendererSpecificResourcePage(this, emptyList(), RenderingStrategy.Copy("/dokka/$this"))
